import { RouteRecordRaw, createRouter, createWebHistory } from 'vue-router'
import { lStorage } from '@/utils/storage'
import { store } from '@/store'
import { getRoutes } from './static.js'
import NProgress from 'nprogress'

// 原始全局布局组件
const Layout = () =>
	import(/* webpackChunkName: "layout" */ '@/page/layout/index.vue').then(
		(m) => m.default
	)

// 静态路由
const staticRoutes: RouteRecordRaw[] = [
	{
		path: '/',
		redirect: '/index',
	},
	{
		path: '/404',
		component: () => import('@/page/error/404.vue'),
		meta: { hidden: true, title: '404' },
	},
]

// 布局下的静态子路由
const childRoutes = [
	{
		path: '/index',
		name: 'index',
		component: () => import('@/views/index.vue'),
		meta: {
			hidden: false,
			title: '首页',
			keepAlive: true,
			icon: 'dashboard',
			hasPerm: ['viewHome'],
			affix: true, // 固定在标签栏
		},
	},
]

// 合并静态路由
const routes = [
	...staticRoutes,
	{ path: '/', component: Layout, name: 'layout', children: childRoutes },
]

// 创建路由实例
const router = createRouter({
	history: createWebHistory(),
	routes: routes,
	scrollBehavior(to, from, savedPosition) {
		// 检查目标路径是否为空字符串或匹配空路径的路由
		if (to.path === '' || to.matched.some((record) => record.path === '')) {
			return false // 阻止滚动
		}
		if (savedPosition) {
			return savedPosition
		} else {
			return { top: 0 }
		}
	},
})

// 动态路由加载完成标志
let isDynamicRoutesLoaded = false

// 路由守卫
router.beforeEach(async (to, from, next) => {
	if (to.path.includes('Solution')) {
		return next(false)
	}

	const routesStore = store.useRoutesStore()

	NProgress.start() // 开始进度条

	// 动态路由加载逻辑
	if (!isDynamicRoutesLoaded) {
		try {
			// 加载动态路由
			const dynamicRoutes = Array.isArray(lStorage.get('WX_WX_USER_ROUTES'))
				? lStorage.get('WX_WX_USER_ROUTES')
				: await getRoutes()
			await routesStore.addRoutes(dynamicRoutes) // 动态添加路由

			isDynamicRoutesLoaded = true // 设置标志，避免重复加载
			NProgress.done()
			// 确保目标路径有效
			return next({ path: to.fullPath, replace: true })
		} catch (error) {
			console.error('Failed to load dynamic routes:', error)
			NProgress.done()
			// return next('/404') // 出现异常时跳转到 404
			return next()
		}
	}

	// 更新 Tabs 状态
	const tabsStore = store.useTabsStore()
	if (!to.matched.length) {
		NProgress.done()
		// return next('/404') // 如果目标路由无匹配，跳转到 404
		return next()
	}
	tabsStore.addTab(to)
	tabsStore.setActiveTab(to.path)

	NProgress.done()
	next()
})

// 路由重置函数
export function resetRouter() {
	try {
		isDynamicRoutesLoaded = false // 重置动态路由加载状态
		router.getRoutes().forEach((route) => {
			if (route.name && route.name !== 'layout') {
				router.hasRoute(route.name) && router.removeRoute(route.name)
			}
		})
		childRoutes.forEach((item) => {
			router.addRoute('layout', item)
		})
	} catch (error) {
		console.error('Error during router reset:', error)
	}
}

// 全局后置钩子
router.afterEach(() => {
	NProgress.done() // 结束进度条
})

export default router
